package Game;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.Timer;
import java.util.TimerTask;
import java.util.List;
import java.util.ArrayList;
import java.util.Random;

public class FishPanel extends JPanel implements MouseListener,MouseMotionListener {
    //属性
    Cannon cannon = new Cannon();
    Image bgImg = new ImageIcon("img/sea.png").getImage();
    //子弹
    private List<Bullet> bullets = new ArrayList<>();
    //鱼
    private List<Fish> fishes = new ArrayList<>();
    private Random random = new Random();
    private int frameCount = 0;
    //记录总分数
    private int totalScore = 0;

    //构造
    public FishPanel(){
        this.addMouseMotionListener(this);
        this.addMouseListener(this);
        // 初始化随机鱼
        for (int i = 0; i < 30; i++) {
            addRandomFish();
        }
    }
    public void paint(Graphics g){
        super.paint(g);
        // 绘制背景图片并填充整个面板
        Graphics2D g2d = (Graphics2D) g;
        int width = getWidth();
        int height = getHeight();
        // 启用抗锯齿，使旋转后的图片更平滑
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        // 绘制背景
        g2d.drawImage(bgImg, 0, 0, width, height, null);
        // 绘制子弹
        for (Bullet bullet : bullets) {
            g.drawImage(bullet.getImg(), bullet.getX(), bullet.getY(), null);
        }
        // 绘制鱼
        for (Fish fish : fishes) {
            Image img = fish.getCurrentImage();
            if (img!= null) {
                int x = fish.getX();
                int y = fish.getY();
                g2d.drawImage(img, x - img.getWidth(null)/2, y - img.getHeight(null)/2, null);
            } else {
                System.err.println("");
            }
        }
        // 绘制旋转后的炮
        Image cannonImg = cannon.getRotatedImage();
        int cannonWidth = cannonImg.getWidth(null);
        int cannonHeight = cannonImg.getHeight(null);
        g2d.drawImage(cannonImg, cannon.x - cannonWidth/2, cannon.y - cannonHeight/2, null);
        // 绘制左上角总分数
        g2d.setColor(Color.WHITE);
        g2d.setFont(new Font("宋体", Font.BOLD, 16));
        g2d.drawString("总分数: " + totalScore, 10, 20);
    }
    // 碰撞检测方法
    private boolean isColliding(Bullet bullet, Fish fish) {
        int bulletX = bullet.getX();
        int bulletY = bullet.getY();
        int fishX = fish.getX();
        int fishY = fish.getY();
        int fishWidth = fish.getWidth();
        int fishHeight = fish.getHeight();
        return bulletX >= fishX && bulletX <= fishX + fishWidth &&
                bulletY >= fishY && bulletY <= fishY + fishHeight;
    }
    // 一颗子弹只命中一条鱼
    private void checkBulletFishCollision() {
        List<Bullet> bulletsToRemove = new ArrayList<>();
        List<Fish> fishesToRemove = new ArrayList<>();

        for (Bullet bullet : bullets) {
            for (Fish fish : fishes) {
                if (isColliding(bullet, fish)) {
                    fish.setDead();
                    bulletsToRemove.add(bullet);
                    // 直接标记鱼为待移除
                    fishesToRemove.add(fish);
                    //累加分数
                    totalScore += fish.getScoreValue();
                    break;
                }
            }
        }

        bullets.removeAll(bulletsToRemove);
        // 移除被击中的鱼
        fishes.removeAll(fishesToRemove);
    }
    //启动游戏
    public void action(){
        Timer timer = new Timer();
        timer.schedule(new TimerTask(){
            public void run(){
                frameCount++;
                //子弹变动
                updateBullets();
                updateFishes();
                removeOutOfBoundsFishes();
                checkBulletFishCollision();
                // 每30帧添加一条新鱼，保持鱼群数量
                if (frameCount % 30 == 0 && fishes.size() < 30) {
                    addRandomFish();
                }
                repaint();
            }

        },0,10);
    }
    //增添鱼
    private void addRandomFish() {
        int fishType = random.nextInt(6) + 1; // 1-6种鱼
        fishes.add(new Fish(fishType));
    }
    private void updateFishes() {
        for (Fish fish : fishes) {
            fish.update();
        }
    }
    private void removeOutOfBoundsFishes() {
        for (int i = 0; i < fishes.size(); i++) {
            Fish fish = fishes.get(i);
            if (fish.isOutOfBounds(getWidth(), getHeight())) {
                fishes.remove(i);
                i--;
            }
        }
    }

    //子弹变动
    private void updateBullets() {
        for (int i = 0; i < bullets.size(); i++) {
            Bullet bullet = bullets.get(i);
            bullet.update();
            // 移除超出边界的子弹
            if (bullet.getX() < 0 || bullet.getX() > getWidth() ||
                    bullet.getY() < 0 || bullet.getY() > getHeight()) {
                bullets.remove(i);
                i--;
            }
        }
    }
    // 计算炮的中心点作为子弹起始位置
    int cannonCenterX = cannon.x + cannon.img.getWidth(null) / 2 - 5;
    int cannonCenterY = cannon.y - 5;
    // 判断是否点击了炮
    private boolean isCannonClicked(int x, int y) {
        // 假设炮的大小为100x100像素，根据实际情况调整
        return x >= cannon.x - 50 && x <= cannon.x + 50 &&
                y >= cannon.y - 50 && y <= cannon.y + 50;
    }

    @Override
    public void mouseDragged(MouseEvent e) {

    }

    @Override
    public void mouseMoved(MouseEvent e) {
        // 当鼠标移动时，更新炮口方向
        int mouseX = e.getX();
        int mouseY = e.getY();
        cannon.calculateRotation(mouseX, mouseY);
        repaint();
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        int startX = cannon.x;
        int startY = cannon.y;
        int clickX = e.getX();
        int clickY = e.getY();
        // 检测是否点击了炮
        // 点击炮后直接返回，不发射子弹
        if (isCannonClicked(clickX, clickY)) {
            cannon.nextImage();
            repaint();
            return;
        }
        // 判断点击位置是否在cannon范围内，这里简单假设cannon图片大小为100x100，可根据实际调整
        if (clickX >= cannon.x -50 && clickX <= cannon.x + 50 && clickY >= cannon.y - 50 && clickY <= cannon.y + 50) {
            cannon.nextImage();
            repaint(); // 重新绘制界面，显示切换后的图片
        }
        // 根据炮当前的图片索引获取对应的子弹图片
        int bulletImgIndex = cannon.currentImgIndex;
        Image bulletImg = new ImageIcon("img/bullet" + (bulletImgIndex + 1) + ".png").getImage();
        Bullet bullet = new Bullet(cannonCenterX, cannonCenterY, clickX - cannonCenterX, clickY - cannonCenterY, bulletImg);
        bullets.add(bullet);
    }

    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }

}
